<template>
  <div class="test-question-list">
    <el-card shadow="never" style="margin-bottom: 20px; border: none">
      <el-form :inline="true" :model="pageInfo" class="demo-form-inline">
        <el-form-item label="题目内容">
          <el-input
            v-model="pageInfo.topic"
            placeholder="根据题目内容搜索"
            clearable
            class="search-ipt"
          />
        </el-form-item>
        <el-form-item label="题目类型">
          <el-select v-model="pageInfo.type" placeholder="请选择">
            <el-option
              v-for="item in testQuestionTypeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="search-warp">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
            >搜索</el-button>
            <el-button type="danger" @click="resetSearchInfo">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" style="border: none">
        <div class="header-warp">
          <div style="display: flex">
            <el-button
              v-if="!paperId"
              text
              type="primary"
              icon="el-icon-plus"
              @click="createTestQuestions"
            >
              创建题目
            </el-button>

            <el-button
              v-if="!paperId"
              text
              type="danger"
              icon="el-icon-delete"
              :disabled="currentItem.length <= 0"
              @click="batchDeletion"
            >
              批量删除
            </el-button>

            <el-button
              v-if="paperId"
              :loading="addAnswerLoading"
              text
              type="success"
              icon="el-icon-circle-plus"
              :disabled="currentItem.length <= 0"
              @click="handleAddAnswerToPaper"
            >
              批量加入试卷
            </el-button>

            <el-button
              v-if="!paperId"
              :loading="addAnswerLoading"
              text
              type="primary"
              icon="el-icon-search"
              @click="selectTypeScore"
            >
              查看题目类型分数
            </el-button>
            <ImportOperation
              ref="importOperationRef"
              dialog-title="题目导入"
              :topic-tabel="topicTabel"
              :sample-file-down-load-addr="sampleFileDownLoadAddr"
              @uploadSuccess="handleUploadSuccess"
              @handleSumbits="handleUploadSumbits"
            >
              导入题目
            </ImportOperation>
            <el-button
              type="primary"
              icon="el-icon-download"
              :disabled="currentItem.length <= 0"
              @click="handleExportTopic"
            >
              导出题目
            </el-button>
          </div>
        </div>
      <el-table
        ref="elTableRef"
        v-loading="loading"
        style="width: 100%"
        :row-key="getRowKey"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        />
        <el-table-column
          v-for="(item, index) in options"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          align="center"
          :show-overflow-tooltip="item.prop !== 'action'"
        >
          <template v-if="item.prop === 'type'" v-slot="{ row }">
            <div>
              <el-tag type="success">
                {{ row.type.name }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!paperId"
          align="center"
          prop="action"
          label="操作"
        >
          <template v-slot="{ row }">
            <el-button
              type="text"
              size="medium"
              @click="editTestQuestions(row)"
            >
              编辑
            </el-button>
            <!-- <el-button
                type="text"
                size="medium"
                style="margin: 10px"
                @click="editAnswer(row)"
              >
                修改答案
              </el-button> -->
            <el-popconfirm
              title="确定删除该道题吗？"
              @confirm="deleteTestQuestion(row)"
            >
              <el-button
                slot="reference"
                type="text"
                size="medium"
                style="color: #ff4949;margin: 10px"
              >
                删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-warp">
        <el-pagination
          :current-page="pageInfo.page"
          :page-sizes="[10, 20, 30]"
          :page-size="pageInfo.paginate"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :title="form.id ? '修改题目' : '创建题目'"
      width="600px"
      class="test-dialog"
    >
      <el-form
        ref="formRef"
        label-position="left"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="题目类型" prop="type_id">
          <el-select
            v-model="form.type_id"
            :disabled="form.id ? true : false"
            placeholder="请选择"
            @change="selectChange"
          >
            <el-option
              v-for="item in testQuestionTypeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="topic">
          <el-input
            v-model="form.topic"
            placeholder="请输入题目内容"
            type="textarea"
          />
        </el-form-item>
        <!-- <el-form-item label="分数" prop="score">
          <el-input-number v-model="form.score" :min="1" label="题目分数" />
        </el-form-item> -->
        <template v-if="!form.id">
          <el-form-item
            v-for="(item, index) in form.answer"
            :key="index"
            :label="`选项${index + 1}`"
            :prop="'answer.' + index + '.content'"
            :rules="{
              required: true,
              message: '选项内容不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <div class="answer-box">
              <el-input
                v-model="item.content"
                autosize
                placeholder="请输入选项内容"
                type="textarea"
              />
              <div class="btn-box">
                <el-tooltip
                  :enterable="false"
                  class="item"
                  effect="dark"
                  content="删除选项"
                  placement="top"
                >
                  <el-button
                    circle
                    type="danger"
                    icon="el-icon-delete"
                    @click.prevent="removeAnswer(item)"
                  />
                </el-tooltip>
                <el-tooltip
                  :enterable="false"
                  class="item"
                  effect="dark"
                  content="设为答案"
                  placement="top"
                >
                  <el-button
                    circle
                    type="warning"
                    :icon="answerIcon(item)"
                    @click.prevent="setTheAnswer(item, index)"
                  />
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
        </template>
        <!-- <template >
        </template> -->
      </el-form>
      <el-form
        v-if="form.id"
        ref="formRef"
        v-loading="loading"
        label-position="left"
        :model="form"
        class="form-warp"
        label-width="100px"
      >
        <el-form-item
          v-for="(item, index) in form.answer"
          :key="index"
          :label="`答案内容${index + 1}`"
          :prop="'answer.' + index + '.content'"
          :rules="{
            required: true, message: '答案内容不能为空', trigger: ['blur', 'change']
          }"
        >
          <div class="answer-box">
            <div style="flex: 1;">
              <el-input
                v-if="item.id"
                v-model="item.content"
                autosize
                placeholder="请输入答案内容"
                type="textarea"
                :readonly="item.id !== answerId"
              />
              <el-input
                v-if="!item.id"
                v-model="item.content"
                autosize
                placeholder="请输入答案内容"
                type="textarea"
              />
            </div>
            <div class="btn-box">
              <template v-if="item.id && item.id !== answerId">
                <el-tooltip :enterable="false" class="item" effect="dark" content="编辑" placement="top-start">
                  <el-button type="primary" icon="el-icon-edit" circle @click="editAnswers(item)" />
                </el-tooltip>
                <el-tooltip :enterable="false" class="item" effect="dark" content="删除" placement="top-start">
                  <el-button type="danger" icon="el-icon-delete" circle @click="deleteAnswer(item)" />
                </el-tooltip>
                <el-tooltip :enterable="false" class="item" effect="dark" content="设为答案" placement="top-start">
                  <el-button type="warning" :icon="item.is_ok === 1 ? 'el-icon-star-on' : 'el-icon-star-off'" circle @click="setAnswer(item)" />
                </el-tooltip>
              <!-- <div style="display: flex; align-items: center;">
                <span style="margin: 0 10px;">答案</span>
                <el-switch
                  v-model="item.is_ok"
                />
              </div> -->
              </template>
              <template v-if="!item.id || item.id === answerId">
                <el-button type="primary" icon="el-icon-check" circle @click="submitChange(item)" />
                <el-button type="danger" icon="el-icon-close" circle @click="handleCancel(item)" />
              </template>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div class="btn-box">
        <el-button
          class="del-button"
          type="primary"
          :loading="btnLoading"
          @click="submitTestQuestion"
        >
          {{ form.id ? "修改" : "提交" }}
        </el-button>
        <el-button
          class="del-button"
          type="primary"
          @click="addAnswer"
        >
          添加选项
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="查看题目分数"
      :visible.sync="selectTypeShow"
      :close-on-click-modal="false"
      width="30%"
    >
      <el-form
        v-for="(item, index) in selectTypeDate"
        ref="form"
        :key="index"
        :model="item"
        label-width="80px"
      >
        <el-form-item label="题目类型">
          <el-input v-model="item.name" disabled />
        </el-form-item>
        <el-form-item label="题目分数">
          <el-input v-model="item.scores.score" />
          <!-- <span v-else>暂无数据</span> -->
        </el-form-item>
        <el-form-item label="操作">
          <el-button
            type="primary"
            @click="updateScore(item, index)"
          >修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <editAnswerDialog
      :show.sync="editAnswerShow"
      :test-question-id="testQuestionId"
    />
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="deleteErrorShow"
      title="删除失败"
      width="800px"
      @closed="deleteErrorCloseCallback"
    >
      <div>
        <div class="del-num" style="margin-bottom: 20px">
          <el-tag>
            已删除：{{
              deleteItemInfo.delList.length -
                deleteItemInfo.deletionFailureList.length
            }}
          </el-tag>
          <el-tag type="danger" style="margin-left: 20px">
            删除失败：{{ deleteItemInfo.deletionFailureList.length }}
          </el-tag>
        </div>
        <el-table
          :data="deleteItemInfo.deletionFailureList"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="type" label="题目类型" align="center">
            <template v-slot="{ $index }">
              <el-tag type="success">
                {{ deleteItemInfo.deletionFailureList[$index]["type"].name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="topic" label="题目内容" align="center" />
          <el-table-column prop="score" label="分数" align="center" />
          <el-table-column prop="action" label="失败原因" align="center">
            <template v-slot="{ row }">
              <el-tag type="danger">
                {{ failedReason(row.id) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div style="display: flex; justify-content: flex-end">
          <el-button text type="danger" icon="el-icon-delete" @click="redelete">
            重新删除
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="editSubjectScoreShow"
      title="修改题目分数"
      width="500px"
      @closed="editSubjectScoreClosed"
    >
      <div class="edit-subject-score">
        <el-form
          ref="editScoreForm"
          label-position="left"
          :model="editSubjectFormData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="题目类型" prop="type_id">
            <el-select
              v-model="editSubjectFormData.type_id"
              placeholder="请选择"
              @change="selectChangeOfEditSubjectScore"
            >
              <el-option
                v-for="item in testQuestionTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="题目分数"
            prop="score"
            :rules="{
              required: true,
              message: '题目分数不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <div style="width: 300px">
              <el-input-number v-model="editSubjectFormData.score" :min="1" />
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <!-- <el-button @click="dialogVisible">取 消</el-button> -->
          <el-button
            :loading="editSubjectLoading"
            type="primary"
            @click="editSubjectApi"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <addAnswerToPaper
      :show.sync="addAnswerToPaper"
      :paper-id="paperId / 1"
      :subject-list="currentItem"
    /> -->
  </div>
</template>

<script>
import lodash from 'lodash'
import { scrollTo } from '@/utils/scroll-to'
import editAnswerDialog from './components/editAnswerDialog.vue'
import ImportOperation from '@/views/examination/components/ImportOperation.vue'
import {
  getTestQuestionList,
  createTestQuestion,
  editTestQuestion,
  deleteTestQuestion,
  getTestQuestionType,
  batchDeletionTestQusetion,
  detailsPaper,
  addSubjecttoPaper,
  editSubjectScore,
  importTopic,
  exportTopic,
  analysisTopic,
  importanAlysisPaper
} from '@/api/examination'
import { options } from './js/options'
export default {
  name: 'TestQuestionList',
  components: {
    editAnswerDialog,
    ImportOperation
    // addAnswerToPaper
  },
  data() {
    return {
      sampleFileDownLoadAddr:
        'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/test_1688710432_8se2Ey56SJ.xlsx',
      editSubjectLoading: false,
      editSubjectFormData: {
        type_id: 1,
        score: 0
      },
      editSubjectScoreShow: false,
      addAnswerLoading: false,
      deleteErrorShow: false,
      editAnswerShow: false,
      addAnswerToPaper: false,
      tableData: [],
      options: options,
      pageInfo: {
        paginate: 10,
        page: 1,
        total: 1,
        topic: '',
        type: null
        // score: null
      },
      loading: false,
      btnLoading: false,
      dialogVisible: false,
      form: {
        type_id: null,
        topic: '', // 题目内容
        // score: 1, // 分数
        answer_index: null, // 答案下标
        answer: [{ content: '' }] // 答案内容
      },
      rules: {
        type_id: [
          {
            required: true,
            message: '请选择题目类型',
            trigger: ['blur', 'change']
          }
        ],
        topic: [
          {
            required: true,
            message: '请输入题目内容',
            trigger: ['blur', 'change']
          }
        ]
        // score: [{ required: true, message: '请输入题目分数', trigger: ['blur', 'change'] }]
      },
      testQuestionId: null,
      testQuestionTypeOption: null,
      testQuestionType: '',
      currentItem: [],
      deleteItemInfo: {
        deleteList: [],
        deletionFailureList: [],
        boundIds: [],
        delList: []
      },
      paperId: null,
      selectTypeShow: false,
      selectTypeDate: [],
      topicTabel: [],
      scoresNull: ''
    }
  },
  computed: {
    answerIcon() {
      return (item) => {
        const index = this.form.answer.indexOf(item)
        if (index !== -1) {
          if (this.testQuestionType === 'multiple_selection') {
            return this.form.answer_index.includes(index)
              ? 'el-icon-star-on'
              : 'el-icon-star-off'
          } else {
            return index === this.form.answer_index
              ? 'el-icon-star-on'
              : 'el-icon-star-off'
          }
        } else return 'el-icon-star-off'
      }
    },
    failedReason() {
      return (id) => {
        return this.deleteItemInfo.boundIds.includes(id)
          ? '已绑定试卷'
          : '删除失败'
      }
    }
  },
  created() {
    // this.getTestList()
    this.paperId = this.$route.query.paper_id
    this.init()
  },
  methods: {
    getRowKey(row) {
      return row.id
    },
    resetSearchInfo() {
      this.pageInfo = this.$options.data().pageInfo
      this.getTestList()
    },
    handleSearch() {
      this.pageInfo.page = 1
      this.getTestList()
    },

    async init() {
      await Promise.allSettled([this.getTestList(), this.getTestTypeList()])
    },

    paramsFormat(params) {
      const a = params
      Object.keys(a).forEach((item) => {
        if ((item === null) | (item === '')) delete a[item]
      })
      return a
    },

    async getTestList() {
      this.loading = true
      const { page, paginate, topic, type } = this.pageInfo
      let params = this.paramsFormat({ page, paginate, topic, type })
      params = this.paperId ? { ...params, paper_id: this.paperId } : params

      // this.paperId
      //   ? { page, paginate, topic, paper_id: this.paperId }
      //   : { page, paginate, topic }
      try {
        const res = await getTestQuestionList(params)
        this.tableData = res.data
        this.pageInfo.total = res.meta.total
      } catch (error) {
        this.$message.error('获取题目列表失败!')
      } finally {
        this.loading = false
      }
    },

    async getTestTypeList() {
      try {
        const res = await getTestQuestionType()
        this.selectTypeDate = res.data.map((item) => {
          return {
            ...item,
            scores: item.scores ? item.scores : { score: 0 }
          }
        })
        this.testQuestionTypeOption = res.data.map((item) => {
          return {
            value: item.id,
            label: item.name,
            type: item.type,
            scores: item.scores ? item.scores : { scores: 0 }
          }
        })
        console.log(this.selectTypeDate)
      } catch (error) {
        console.log('error ------>', error)
      }
    },

    handleSizeChange(e) {
      this.pageInfo.paginate = e
      this.pageInfo.page = 1
      this.getTestList()
      scrollTo(0, 800)
    },

    handleCurrentChange(e) {
      this.pageInfo.page = e
      this.getTestList()
      scrollTo(0, 800)
    },

    createTestQuestions() {
      this.dialogVisible = true
      this.testQuestionType = ''
      this.form = this.$options.data().form
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    },

    addAnswer() {
      this.form.answer.push({
        content: ''
      })
    },
    setTheAnswer(item, index) {
      // const index = this.form.answer.indexOf(item)
      switch (this.testQuestionType) {
        case 'single_option':
          this.form.answer_index =
            index === this.form.answer_index ? null : index
          break
        case 'multiple_selection':
          if (this.form.answer_index.includes(index)) {
            const i = this.form.answer_index.indexOf(index)
            this.form.answer_index.splice(i, 1)
          } else {
            this.form.answer_index.push(index)
          }
          break
        default:
          this.form.answer_index =
            index === this.form.answer_index ? null : index
          break
      }
    },

    removeAnswer(item) {
      this.$confirm('是否删除该项答案', '提示', { type: 'warning' }).then(
        () => {
          const index = this.form.answer.indexOf(item)
          if (index !== -1) {
            if (index === this.form.answer_index) this.form.answer_index = null
            this.form.answer.splice(index, 1)
          }
        }
      )
    },

    formatParams() {
      return {
        ...this.form,
        answer: JSON.stringify(this.form.answer),
        answer_index:
          this.testQuestionType === 'multiple_selection'
            ? JSON.stringify(this.form.answer_index)
            : this.form.answer_index
      }
    },

    submitCheck() {
      if (this.form.answer.length <= 0) {
        this.$message.error('请添加选项！！！')
        throw new Error('form answer is required')
      }
      switch (this.testQuestionType) {
        case 'multiple_selection':
          if (this.form.answer.length < 3) {
            this.$message.error('多选题选项至少为3项')
            throw new Error('multiple choice options should be at least 3 ')
          }
          if (this.form.answer_index.length < 2) {
            this.$message.error('多选题答案至少为2项')
            throw new Error('multiple choice answers should be at least 2 ')
          }

          break
        case 'single_option':
          if (this.form.answer.length < 2) {
            this.$message.error('单选题选项至少为2项')
            throw new Error('single choice options should be at least 2 ')
          }
          break
      }
      if (this.form.answer_index === null) {
        this.$message.error('请为题目设置答案！！！')
        throw new Error('form answer_index is required')
      }
    },

    async submitTestQuestion() {
      this.$refs.formRef?.validate(async(valid) => {
        if (!valid) return
        if (!this.form.id) this.submitCheck()
        if (!this.form.id) this.createTestQuestionApi()
        else this.editTestQuestionApi()
      })
    },

    // 创建题目API
    async createTestQuestionApi() {
      this.btnLoading = true
      try {
        const res = await createTestQuestion(this.formatParams())
        if (res.status === 'success') {
          this.$message.success('题目创建成功')
          // this.pageInfo.page = 1
          this.getTestList()
        }
      } catch (error) {
        this.$message.error('题目创建失败')
      } finally {
        this.btnLoading = false
        this.dialogVisible = false
      }
    },

    // 修改题目API
    async editTestQuestionApi() {
      this.btnLoading = true
      const { id, topic } = this.form
      try {
        const res = await editTestQuestion({ id, topic })
        if (res.status === 'success') {
          this.$message.success('题目修改成功')
          // this.pageInfo.page = 1
          this.getTestList()
        }
      } catch (error) {
        this.$message.error('题目修改失败')
      } finally {
        this.btnLoading = false
        this.dialogVisible = false
      }
    },

    async deleteTestQuestion(row, del = 0) {
      const { id } = row
      try {
        const res = await deleteTestQuestion({ id, delete: del })
        if (res.data.status === 'bound') {
          this.$confirm('该道题目已经添加到试卷中了，是否继续删除', '提示', {
            type: 'warning'
          }).then(() => {
            this.deleteTestQuestion(row, 1)
          })
          return
        }
        if (res.status === 'success') {
          this.$message.success('删除成功')
          this.getTestList()
        }
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    editTestQuestions(row) {
      const a = lodash.cloneDeep(row)
      this.form.id = a.id
      this.form.topic = a.topic
      // this.form.score = a.score
      this.form.type_id = a.type.id
      this.form.answer_index = a.answer_index
      this.form.answer = a.content
      this.dialogVisible = true
    },

    editAnswer(item) {
      this.testQuestionId = item.id
      this.editAnswerShow = true
    },
    editAnswers(item) {
      console.log('item ------>', item)
      this.answerId = item.id
      this.currentAnswer = lodash.cloneDeep(item)
    },
    handleCancel(item) {
      const index = this.form.answer.indexOf(item)
      if (item.id) {
        this.answerId = null
        this.form.answer[index] = this.currentAnswer
      } else {
        if (index !== -1) {
          this.form.answer.splice(index, 1)
        }
      }
    },

    submitChange(item) {
      this.$refs.formRef?.validate(valid => {
        if (!valid) return
        let params = {}
        params = item.id
          ? {
            id: item.id,
            content: item.content,
            is_ok: item.is_ok
          }
          : {
            topic_id: this.form.id,
            content: item.content,
            is_ok: 0
          }
        this.editOrCreateAnswerApi(params)
      })
    },
    async editOrCreateAnswerApi(params, refresh = true) {
      try {
        const res = await editOrCreateAnswer(params)
        console.log('res editOrCreateAnswerApi ------>', res)
        if (res.status === 'success') {
          this.$message.success('修改成功')
          this.reset(refresh)
        }
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    reset(refresh = false) {
      this.answerId = null
    },
    deleteAnswer(item) {
      this.$confirm('是否删除该项答案', '提示', { type: 'warning' })
        .then(() => {
          const index = this.form.answer.indexOf(item)
          if (index !== -1) {
            this.form.answer.splice(index, 1)
            this.deleteAnswerApi(item.id)
          }
        })
    },

    async deleteAnswerApi(id) {
      try {
        const res = await deleteAnswer({ id })
        if (res.status === 'success') this.$message.success('删除成功')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    setAnswer(item) {
      item.is_ok = item.is_ok === 1 ? 0 : 1
      const params = item.id
        ? {
          id: item.id,
          content: item.content,
          is_ok: item.is_ok
        }
        : {
          topic_id: this.testQuestionId,
          content: item.content
        }

      this.editOrCreateAnswerApi(params, true)
    },

    selectChange(e) {
      this.testQuestionType = this.testQuestionTypeOption.filter(
        (item) => item.value === e
      )[0].type
      this.form.answer_index =
        this.testQuestionType === 'multiple_selection' ? [] : null
    },

    // 多选
    handleSelectionChange(e) {
      if (this.paperId) {
        this.currentItem = e.map((item, index) => {
          return { ...item, order: index + 1 }
        })
      } else this.currentItem = e.map((item) => item.id)
      this.deleteItemInfo.deleteList = e
    },

    redelete() {
      const ids = this.deleteItemInfo.deletionFailureList.map(
        (item) => item.id
      )
      this.$confirm('是否继续删除？', '提示', { type: 'warning' }).then(() => {
        this.batchDeletionApi(JSON.stringify(ids), 1)
      })
    },

    async batchDeletion() {
      this.$confirm('是否删除所选中的题目', '提示', { type: 'warning' }).then(
        () => {
          const ids = JSON.stringify(this.currentItem)
          this.deleteItemInfo.delList = this.currentItem
          this.batchDeletionApi(ids)
        }
      )
    },

    async batchDeletionApi(ids, del = 0) {
      try {
        const res = await batchDeletionTestQusetion({ id: ids, delete: del })
        if (res.data?.bound.length > 0 || res.data?.error.length > 0) {
          this.deleteItemInfo.boundIds = res.data.bound
          res.data.error.forEach((item) => {
            this.deleteItemInfo.deleteList.forEach((items) => {
              if (item === items.id) {
                this.deleteItemInfo.deletionFailureList.push(items)
              }
            })
          })
          this.getTestList()
          this.deleteErrorShow = true
        } else if (res.status === 'success') {
          this.$message.success('删除成功')
          this.getTestList()
          this.deleteErrorShow = false
        }
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    deleteErrorCloseCallback() {
      this.deleteItemInfo.boundIds = []
      // this.deleteItemInfo.deleteList = []
      this.deleteItemInfo.deletionFailureList = []
    },
    async getPaperDetail() {
      return new Promise((reslove, reject) => {
        detailsPaper(this.paperId)
          .then((res) => {
            reslove(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    async handleAddAnswerToPaper() {
      this.addAnswerLoading = true
      try {
        const res = await this.getPaperDetail()
        const { topic } = res.data
        this.currentItem.forEach((item) => {
          item.order = item.order + topic.length
        })
        const topic_id = this.currentItem.map((item) => {
          return { order: item.order, id: item.id }
        })
        const params = {
          paper_id: this.paperId,
          topic_id: JSON.stringify(topic_id)
        }
        this.addSubjecttoPaperApi(params)
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.addAnswerLoading = false
      }
    },

    async addSubjecttoPaperApi(params) {
      try {
        const res = await addSubjecttoPaper(params)
        if (res.status === 'success') {
          this.$message.success('添加成功')
          this.getTestList()
        }
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    editScore() {
      this.editSubjectScoreShow = true
      this.editSubjectFormData.score = this.testQuestionTypeOption.find(
        (item) => item.value === this.editSubjectFormData.type_id
      ).scores.score
    },
    selectTypeScore() {
      this.selectTypeShow = true
    },
    selectChangeOfEditSubjectScore(e) {
      this.editSubjectFormData.type_id = this.testQuestionTypeOption.find(
        (item) => item.value === e
      ).value
      this.editSubjectFormData.score = this.testQuestionTypeOption.find(
        (item) => item.value === e
      ).scores.score
    },
    async editSubjectApi() {
      await this.$refs.editScoreForm.validate()
      this.editSubjectLoading = true
      try {
        const res = await editSubjectScore(this.editSubjectFormData)
        if (res.status === 'success') {
          this.$message.success('修改成功')
          this.editSubjectScoreShow = false
          this.init()
        }
      } catch (error) {
        this.$message.error('修改失败')
      } finally {
        this.editSubjectLoading = false
      }
    },
    editSubjectScoreClosed() {
      this.editSubjectFormData = this.$options.data().editSubjectFormData
    },
    async updateScore(item, index) {
      try {
        const params = {
          type_id: item.id,
          score: item.scores.score
        }
        const res = await editSubjectScore(params)

        if (res.status === 'success') {
          this.$message.success('修改成功')
          this.selectTypeShow = false
          this.init()
        }
      } catch (error) {
        this.$message.error('修改失败')
      }
    },

    async handleUploadSuccess(e) {
      try {
        if (!(e.file instanceof File)) {
          return
        }

        const formData = new FormData()
        formData.append('file', e.file)
        const result = await analysisTopic(formData)
        if (result.code !== 200 || !Array.isArray(result.data)) {
          throw new Error(result.message ?? '解析Excel文件解析失败')
        }
        this.topicTabel = result.data.slice(1).map(item => {
          return {
            topic: item[0],
            option: item[1],
            answer: item[2],
            type: {
              label: item[3],
              value: this.getValue(item[3])
            }
          }
        })
        this.$refs.importOperationRef.isShowUpload = false
      } catch (error) {
        console.log(error)
        const errMsg = error?.response?.data?.message ??
            '解析Excel文件解析失败'
        this.$message.error(errMsg)
      }
      // this.$refs.importOperationRef.isShowUpload=false
      // console.log(e,'e');
      // this.importTopicApi(e)
    },

    async handleUploadSumbits(data) {
      try {
        const res = await importanAlysisPaper(data)
        console.log(res, 'res')
        this.getTestList()
        this.$refs.importOperationRef.show = false
        this.$message.success('导入成功')
      } catch (error) {
        this.$message.error(error.response.data.message || '导入失败')
        this.$refs.importOperationRef.clearUploadedFiles()
      }
    },

    async importTopicApi(data) {
      console.log(data, 'data')
      try {
        const res = await importTopic(data)
        if (res.code === 200) {
          console.log(res)
          this.$message.success('导入成功')
          this.getTestList()
        }
      } catch (error) {
        this.$message.error(error.response.data.message || '导入失败')
        this.$refs.importOperationRef.clearUploadedFiles()
      }
    },

    handleExportTopic() {
      const ids = JSON.stringify(this.currentItem)
      this.exportTopicApi(ids)
    },

    async exportTopicApi(topic) {
      try {
        const res = await exportTopic({ topic })
        if (res.code === 200) {
          this.$message.success('导出成功')
          window.open(res.data.path)
          this.clearSelectionEvent()
        }
      } catch (error) {
        this.$message.error('导出失败')
      }
    },
    clearSelectionEvent() {
      this.$refs.elTableRef.clearSelection()
    },
    getValue(obj) {
      if (obj === '单选') {
        return 1
      } else if (obj === '多选') {
        return 2
      } else if (obj === '判断') {
        return 3
      }
    }
  }
}
</script>
<style scoped lang="scss">
.demo-form-inline{
  .el-form-item{
      margin-bottom: 0px;
  }
}
.test-question-list {
  padding: 20px;

  .search-box {
    //margin: 20px 0;
  }

  .search-warp {
    display: flex;
    align-items: center;

    .title {
      color: #8e8e8e;
      margin-right: 10px;
    }
  }

  .header-warp {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
  }

  .pagination-warp {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .btn-box {
    margin: 0 0 0 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .test-dialog {
    .answer-box {
      display: flex;
    }

    .edit-answer_warp {
      display: flex;
      align-items: center;

      .content {
        padding: 0 10px;
        margin-right: 10px;
        // border-radius: 20px;
        flex: 1;
        border: 1px solid #f2f2f2;
      }
    }
  }

  .del-num {
  }
}
</style>
